package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-mgr/cache"
	"post-mgr/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var posts []models.Post
	redis_list_key := "page_list_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Model(&models.Post{}).Offset(offset).Limit(size).Debug().Find(&posts)
		//转换为json格式
		jsonData, _ := json.Marshal(posts)
		//保存到缓存中
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &posts)
	}
	var total int64
	models.DB.Model(&models.Post{}).Count(&total)

	c.JSON(200, gin.H{
		"message": "登录成功",
		"code":    200,
		"data":    posts,
		"total":   total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	redis_detail_key := "page_list_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if result == "" {
		models.DB.Where("id = ?", id).First(&post)
		//转换为json格式
		jsonData, _ := json.Marshal(post)
		//保存到缓存中
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &post)
	}

	c.JSON(200, gin.H{
		"message": "详情展示成功",
		"code":    200,
		"data":    post,
	})
	return
}
